package com.mission.chronometerandlifecycles

import android.content.Context
import android.os.SystemClock
import android.util.AttributeSet
import android.widget.Chronometer
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent

/**
 * Created by KevenTao on 1/28/21.
 */
class MyChronometer(context: Context, attrs: AttributeSet) : Chronometer(context, attrs),
    LifecycleObserver {
    private var elapsedTime: Long? = null

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    private fun pauseMeter() {
        elapsedTime = SystemClock.elapsedRealtime() - base
        stop()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    private fun resumeMeter() {
        base = SystemClock.elapsedRealtime() - (elapsedTime ?: 0)
        start()
    }
}